package org.feng.navigation.app.generator;

import lombok.extern.slf4j.Slf4j;
import org.feng.navigation.client.api.GeneratorService;
import org.feng.navigation.client.dto.generator.GeneratorCustomEnumRequestDTO;
import org.feng.navigation.client.dto.generator.GeneratorCustomEnumResponseDTO;
import org.feng.navigation.domain.generator.domainobject.EnumBodyObject;
import org.feng.navigation.domain.generator.domainobject.EnumGeneratorObject;
import org.feng.navigation.domain.generator.domainservice.GeneratorApiService;
import org.feng.navigation.generator.definition.EnumFileContentDefinition;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * TODO 类的描述
 *
 * @version V1.0
 * @author: junzi
 * @date: 2023年02月07日 20时25分
 */
@Slf4j
@Service
public class GeneratorServiceImpl implements GeneratorService {

    @Resource
    private GeneratorApiService generatorApiService;

    @Override
    public GeneratorCustomEnumResponseDTO generatorCustomEnum(GeneratorCustomEnumRequestDTO requestDTO) {
        EnumGeneratorObject enumGeneratorObject = new EnumGeneratorObject();
        String text = requestDTO.getText();
        int ketIndex = requestDTO.getKeyIndex();
        // 按照换行符切割
        List<EnumFileContentDefinition> enumFileContentDefinitions = Stream.of(text.split("\r\n")).map(line -> {
            // 按逗号切割
            String[] splitBySpace = line.split(",");
            List<String> contents = new ArrayList<>();
            for (int i = 0; i < splitBySpace.length; i++) {
                if (ketIndex != i) {
                    contents.add(splitBySpace[i]);
                }
            }
            return new EnumFileContentDefinition(splitBySpace[ketIndex], contents);
        }).collect(Collectors.toList());

        // 组装枚举名、参数、注释
        List<EnumBodyObject> enumBodys = enumFileContentDefinitions.stream().map(definition -> {
            EnumBodyObject bodyObject = new EnumBodyObject();
            String pinYinEnumName = definition.getPinYinEnumName();
            bodyObject.setDoc(definition.getOriginChineseBody() + "：" + definition.getKey());
            bodyObject.setBody(pinYinEnumName);
            return bodyObject;
        }).collect(Collectors.toList());
        enumGeneratorObject.setEnumBodyList(enumBodys);
        // 设置枚举类名
        enumGeneratorObject.setCustomEnumClassName(requestDTO.getCustomEnumClassName());
        // 设置枚举类所在的完整包名
        enumGeneratorObject.setFullPackageName(requestDTO.getFullPackageName());
        // 生成完整枚举内容
        generatorApiService.generateCustomEnum(enumGeneratorObject);
        String generatedContent = enumGeneratorObject.getGeneratedContent();
        GeneratorCustomEnumResponseDTO responseDTO = new GeneratorCustomEnumResponseDTO();
        responseDTO.setGeneratedContent(generatedContent);
        return responseDTO;
    }
}
